//
//  HTVideoTableViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTVideoTableViewController.h"
#import "HTVideoTableViewCell.h"
#import "PKRequestManager.h"
#import "HTVideoMainListModel.h"
//#import "UMSocial.h"
#import "MJRefresh.h"
#import "FMDatabase.h"

#import "HTAutherInfoViewController.h"
#define kVideoURL @"http://s.budejie.com/topic/list/jingxuan/41/baisishequ-iphone-3.7/0-20.json?appname=baisishequ&asid=9B8A36AE-96F8-4D1B-8850-D39ECA7F54FD&client=iphone&device=ios%20device&from=ios&jbk=0&mac=&market=&openudid=5fd2dd7c3e13e78bbc5119f9f1405e9ed2bdd82f&udid=&ver=3.7"
#define kVideoURL1 @"http://s.budejie.com/topic/list/jingxuan/41/baisishequ-iphone-3.7/1446023101-20.json?appname=baisishequ&asid=9B8A36AE-96F8-4D1B-8850-D39ECA7F54FD&client=iphone&device=ios%20device&from=ios&jbk=0&mac=&market=&openudid=5fd2dd7c3e13e78bbc5119f9f1405e9ed2bdd82f&udid=&uid=16431595&ver=3.7"
//@interface HTVideoTableViewController ()<UMSocialUIDelegate>
@interface HTVideoTableViewController ()
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) FMDatabase *dataBase; // 数据库
@end

@implementation HTVideoTableViewController
- (NSMutableArray *)dataSourceArray
{
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}

- (void)requestConfigureData:(NSString *)string
{
    [PKRequestManager requestWithType:GET urlString:string parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        [_dataBase executeUpdate:@"DELETE FROM VIDEO"];
        
        for (NSDictionary *dic in dict[@"list"]) {
            HTVideoMainListModel *model = [[HTVideoMainListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:model];
            
            [_dataBase executeUpdate:@"INSERT INTO VIDEO (comment, down, forward, up, text, name, header, image, height, width) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", model.comment, model.down, model.forward, model.up, model.text, model.u.name, model.u.headerArray[0], model.video.thumbnail[0], model.video.height, model.video.width];
        }
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"视频播放界面数据请求失败: %@", error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestConfigureData:kVideoURL];
    [self.tableView registerClass:[HTVideoTableViewCell class] forCellReuseIdentifier:@"HTVideoTableViewCell"];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // 创建一个dataBase可以打开的文件, 用来保存数据
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"Video.db"];
    // 根据路径打开文件, 不存在则创建这个文件
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"========filePath: %@", filePath);
    // 通过open这个方法打开数据库, 打开成功就返回yes, 失败返回no
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"CREATE TABLE VIDEO (comment text, down text, forward text, up text, text text, name text, header text, image text, height integer, width integer)"];
    }else{
        NSLog(@"数据库打开失败");
    }
    
    // 根据查找语句查找表里面的内容
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM VIDEO"];
    while ([resultSet next]) {
        NSString *comment = [resultSet stringForColumn:@"comment"];
        NSString *down = [resultSet stringForColumn:@"down"];
        NSString *forward = [resultSet stringForColumn:@"forward"];
        NSString *up = [resultSet stringForColumn:@"up"];
        NSString *text = [resultSet stringForColumn:@"text"];
        NSString *name = [resultSet stringForColumn:@"name"];
        NSString *header = [resultSet stringForColumn:@"header"];
        NSString *image = [resultSet stringForColumn:@"image"];
        NSNumber *height = [NSNumber numberWithInteger:[resultSet intForColumn:@"height"]];
        NSNumber *width = [NSNumber numberWithInteger:[resultSet intForColumn:@"width"]];
        HTVideoMainListModel *model = [[HTVideoMainListModel alloc]init];
        model.comment = comment;
        model.down = down;
        model.forward = forward;
        model.up = up;
        model.text = text;
        model.u.name = name;
        model.u.headerArray[0] = header;
        model.video.thumbnail[0] = image;
        model.video.height = height;
        model.video.width = width;
        [_dataSourceArray addObject:model];
    }
    [resultSet close];
    [self.tableView reloadData];
    
    // MJRefresh刷新
    __weak HTVideoTableViewController *videoTableVC = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [videoTableVC requestConfigureData:kVideoURL];
        [self.tableView.header endRefreshing];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [videoTableVC requestConfigureData:kVideoURL1];
        [self.tableView.footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.dataSourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HTVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HTVideoTableViewCell" forIndexPath:indexPath];
    // Configure the cell...
    // cell点击后无特效
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    cell.configureModel = model;
    [cell.playButton addTarget:self action:@selector(didClickToPlayVideo:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.videoImageView.userInteractionEnabled = YES;
    cell.playButton.tag = 1000 + indexPath.row;
#warning 判断当前是否添加视频播放器View, 如果添加将其从父视图移除,否则点击某个播放器播放过程中加载cell, 会导致bug
    if (cell.videoImageView.subviews.count > 3) {
        [cell.videoImageView.subviews.lastObject removeFromSuperview];
    }
    // 点击收藏.点赞.差评.分享.评论按钮事件
    [cell.connectionButton addTarget:self action:@selector(didClickToCollection:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.connectionButton.tag = 2000 + indexPath.row;
    [cell.upBLView.button addTarget:self action:@selector(didClickToDianZan:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.upBLView.button.tag = 3000 + indexPath.row;
    [cell.downBLView.button addTarget:self action:@selector(didClickToChaPing:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.downBLView.button.tag = 4000 + indexPath.row;
    [cell.shareBLView.button addTarget:self action:@selector(didClickToShare:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.shareBLView.button.tag = 5000 + indexPath.row;
    [cell.commentBLView.button addTarget:self action:@selector(didClickToCommentView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 给illView添加点击事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapToAutherInfo:)];
    [cell.illView addGestureRecognizer:tap];
    cell.illView.tag = 500 + indexPath.row;
    return cell;
}

- (void)doTapToAutherInfo:(UITapGestureRecognizer *)tap{
    [_moviePlayerController stop];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tap.view.tag - 500 inSection:0];
    HTAutherInfoViewController *autherInfoVC = [[HTAutherInfoViewController alloc]init];
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    autherInfoVC.name = model.u.name;
    autherInfoVC.u_id = model.u.uid;
    [self.videoVC pushViewController:autherInfoVC animated:nil];
}

// 点击播放视频按钮事件
- (void)didClickToPlayVideo:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 1000 inSection:0];
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    HTVideoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    // 初始化播放器
    self.moviePlayerController = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:model.video.video[0]]];
    
    self.moviePlayerController.view.frame = CGRectMake(0, 0, cell.videoImageView.frame.size.width, cell.videoImageView.frame.size.height);
    [cell.videoImageView addSubview:_moviePlayerController.view];
    [self.moviePlayerController play];
    
    //    播放结束的时候添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)playerFinish:(id)sender
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    // 卸载监听, 保证程序不会崩溃
    [_moviePlayerController.view removeFromSuperview];
    _moviePlayerController = nil;// 释放资源
}

- (void)didClickToCollection:(UIButton *)sender
{
    NSLog(@"收藏");
}

- (void)didClickToDianZan:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 3000 inSection:0];
    HTVideoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    [sender setBackgroundImage:[UIImage imageNamed:@"点赞红"] forState:(UIControlStateNormal)];
    cell.upBLView.label.textColor = [UIColor redColor];
    NSInteger up = [model.up integerValue];
    up++;
    cell.upBLView.label.text = [NSString stringWithFormat:@"%ld", up];
}

- (void)didClickToChaPing:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 4000 inSection:0];
    HTVideoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    [cell.downBLView.button setBackgroundImage:[UIImage imageNamed:@"差评红"] forState:(UIControlStateNormal)];
    cell.downBLView.label.textColor = [UIColor redColor];
    NSInteger up = [model.down integerValue];
    up++;
    cell.downBLView.label.text = [NSString stringWithFormat:@"%ld", up];
}

- (void)didClickToShare:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 5000 inSection:0];
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
#warning self.VC  与  self  的区别  此处self会点击分享后弹框frame始终在一个位置
//    [UMSocialSnsService presentSnsIconSheetView:self.VC
//                                         appKey:@"561b79f9e0f55ada8200253c"
//                                      shareText:model.share_url
//                                     shareImage:[UIImage imageNamed:@"icon.png"]
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToRenren,UMShareToSms,UMShareToDouban,UMShareToQQ,nil]
//                                       delegate:self];
}

- (void)didClickToCommentView:(UIButton *)sender
{
    NSLog(@"评论");
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HTVideoMainListModel *model = self.dataSourceArray[indexPath.row];
    return [HTVideoTableViewCell heightForCell:model];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
